package cn.edu.swu.user;

import cn.edu.swu.db.DBEngine;
import cn.edu.swu.db.RecordVisitor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserRepo {
    private static UserRepo instance = new UserRepo();
    private UserRepo() {
    }

    public static UserRepo getInstance() {
        return instance;
    }
    public User auth(String user, String password) throws SQLException {
        String template = "SELECT * FROM `user` WHERE `user` = \"%s\" AND `password` = MD5(\"%s\")";
        List<User> users = DBEngine.getInstance().query(
                String.format(template, user, password), new RecordVisitor<User>() {
                    @Override
                    public User visit(ResultSet rs) throws SQLException {
                        return UserRepo.getUserByResultSet(rs);
                    }
                });
        return users.size() == 0 ? null : users.get(0);
    }
    private static User getUserByResultSet(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setUser(rs.getString("user"));
        user.setPassword(rs.getString("password"));
        return user;
    }

}
